package com.whoyx.jiebing.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.json.JSONUtil;
import com.whoyx.jiebing.dao.entity.UserEntity;
import com.whoyx.jiebing.dao.service.IMsgRecordService;
import com.whoyx.jiebing.dao.service.IUserService;
import com.whoyx.jiebing.domain.resp.*;
import com.whoyx.jiebing.service.PatientService;
import com.whoyx.jiebing.service.HospitalServiceClient;
import com.whoyx.jiebing.utils.*;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
@RequiredArgsConstructor
public class PatientServiceImpl implements PatientService {
    private final IUserService iUserService;
    private final IMsgRecordService iMsgRecordService;
    private final HospitalServiceClient hospitalServiceClient;

    private final RedisCacheUtils redisCacheUtils;

    private final static String SERVICE_HEAD_URL = "https://upload.weiheyixue.com/robot_avatar%402x.png";

    @Override
    public MedicalAdviceRespDto medicalAdvice() {
        return MedicalAdviceRespDto.builder()
                .title("平台使用规则")
                .content("1.门诊当天必须完成随访登记和做问卷模块的填写，方可获得预约挂号奖励。\n" +
                        "2.您至少需要提前两周在复查申请模块提交复诊时间 我们会根据门诊实情况为您预约门诊。\n" +
                        "3.如为您预约门诊后您无法按时就诊，请提前3天在线咨询留言，申请取消预约门诊。\n" +
                        "4.如为您预约门诊后您未按时就诊并未告知我们取消门诊 将视为爽约\n" +
                        "5.此平台只支持一个微信注册，不支持多个微信注册同一患者信息。如多微信注册导致无法预约门诊。\n" +
                        "* 规则1和4如超过三次不规范使用，您将无法使用此平台，请您自行解决挂号问题。")
                .build();
    }

    @Override
    public List<OutpatientServiceRespDto> outpatientServiceInfo() {
        return outpatientServiceInfo(StpUtil.getLoginIdAsString());
    }

    @Override
    public List<OutpatientServiceRespDto> outpatientServiceInfo(String uid) {
        UserEntity userEntity = iUserService.validatedEntityByUid(uid);
        String redisKey = RedisKeyUtil.OutPatientServiceInfo(uid);
        Object object = redisCacheUtils.getCacheObject(redisKey);
        if (object != null) {
            List<OutpatientServiceRespDto> list = JSONUtil.toList(JSONUtil.toJsonStr(object), OutpatientServiceRespDto.class);
            list.forEach(i ->{
                int dayOfWeek = Integer.parseInt(i.getDayOfWeek());
                i.setDayOfWeek(NumberUtil.int2chineseNum(dayOfWeek));
            });
            return list;
        }
        List<OutpatientServiceRespDto> respDtoList = hospitalServiceClient.outpatientServiceInfo(userEntity.getOpenId());
        List<OutpatientServiceRespDto> list = new ArrayList<>(respDtoList.size());
        for (int i = 0; i < respDtoList.size(); i++) {
            OutpatientServiceRespDto outpatientServiceRespDto = respDtoList.get(i);
//            if (i < 2){
//                outpatientServiceRespDto.setStatus("停诊");
//            }
            list.add(outpatientServiceRespDto);
        }
        redisCacheUtils.setCacheObject(redisKey, respDtoList, 6, TimeUnit.HOURS);
        list.forEach(i ->{
            int dayOfWeek = Integer.parseInt(i.getDayOfWeek());
            i.setDayOfWeek(NumberUtil.int2chineseNum(dayOfWeek));
        });
        return list;
    }


    @Override
    public PatientBaseInfoRespDto baseInfo() {
        String uid = StpUtil.getLoginIdAsString();
        String redisKey = RedisKeyUtil.userInfoKey(uid);
        Object object = redisCacheUtils.getCacheObject(redisKey);
        if (object != null) {
            return (PatientBaseInfoRespDto) object;
        }
        UserEntity userEntity = iUserService.validatedEntityByUid(uid);
        PatientBaseInfoRespDto respDto = hospitalServiceClient.patientBaseInfo(userEntity.getOpenId());

//        PatientBaseInfoRespDto respDto = hospitalServiceClient.patientBaseInfo("o6fsjuM0BFN8SKxJE54MOBkwUA2s");
        redisCacheUtils.setCacheObject(redisKey, respDto, 6, TimeUnit.HOURS);
        return respDto;
    }


    @Override
    public BaseUrlRespDto doctorInfo() {
        return BaseUrlRespDto.builder()
                .url("https://b.yicloud.org/dyn2/articleFront/article/articleId/getJump/376")
                .build();
    }

    @Override
    public BaseUrlRespDto questionnaireUrl() {
        return BaseUrlRespDto.builder()
                .url("https://b.yicloud.org/dyn2/wx/2/1643/p/live?opi=o6fsjuJsSpmRE1tf-0dlG7EesEA8")
                .build();
    }

    @Override
    public BaseUrlRespDto uploadPictureUrl() {
        return BaseUrlRespDto.builder()
                .url("https://b.yicloud.org/dyn2/wx/2/1643/p/3157/live?opi=o6fsjuJsSpmRE1tf-0dlG7EesEA8")
                .build();
    }

    @Override
    public List<PopularScienceArticle> popularScienceArticles() {
        List<PopularScienceArticle> articleList = new ArrayList<>(3);
        articleList.add(PopularScienceArticle.builder()
                .title("甲状腺癌患者教育手册—甲状腺癌的病理学分类及意义（一）")
                .url("https://b.yicloud.org/dyn2/articleFront/article/articleId/658?gid=62&configId=2&opi=")
                .build());
        articleList.add(PopularScienceArticle.builder()
                .title("甲状腺癌患者教育手册—甲状腺癌的病理学分类及意义（二）")
                .url("https://b.yicloud.org/dyn2/articleFront/article/articleId/659?gid=62&configId=2&opi=")
                .build());
        articleList.add(PopularScienceArticle.builder()
                .title("甲状腺癌患者教育手册—甲状腺癌的病理学分类及意义（三）")
                .url("https://b.yicloud.org/dyn2/articleFront/article/articleId/660?gid=62&configId=2&opi=")
                .build());

        return articleList;
    }

    public static void main(String[] args) {
        Map<String, String> paramsMap = new HashMap<>();
        paramsMap.put("nonce", "9022081001");
        paramsMap.put("opi", "owUEt1IgepxbkBTVNj8bTMkPlHio");
        String sign = SignUtils.generateSign(paramsMap, "wehe6qJka7jvLqEiytf6AgllYKyLQLA");
        paramsMap.put("sign", sign);
        String respStr = RemoteUtils.sentUrlencodedPost("https://b.yicloud.org/api2/ks/29/data/view", paramsMap);
        System.out.println(respStr);
    }
}
